﻿using BDPAutodetect.Client.ViewWindows.WindowDialog;
using BDPAutodetect.Mgrcore;
using BDPAutodetect.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace BDPAutodetect.Client
{
    /// <summary>
    /// 从机设备设置管理视图模型类
    /// </summary>
    public partial class SettingDeviceSlaveViewModel : BaseViewModel<UserControl>
    {
        /// <summary>
        /// 用户管理实例
        /// </summary>
        protected UserManager UserMgr { get; set; }
        /// <summary>
        /// 从机设备管理实例
        /// </summary>
        protected SlaveManager SlaveMgr { get; set; }
        /// <summary>
        /// 从机设备数据集
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<MSlave> slaveItems;

        /// <summary>
        /// 构造函数
        /// </summary>
        public SettingDeviceSlaveViewModel(UserManager argUserManager, SlaveManager argSlaveManager)
        {
            this.UserMgr = argUserManager;
            this.SlaveMgr = argSlaveManager;
            this.SlaveItems = new ObservableCollection<MSlave>();
        }

        /// <summary>
        /// 初始化加载权限编辑
        /// </summary>
        /// <returns></returns>
        protected async Task InitLoadPermission()
        {
            if (this.PowerPermission == null) return;
            var resultTaskPowers = this.UserMgr.GetUserPowers(this.PowerPermission.Power.ID);
            await resultTaskPowers.ConfigureAwait(false);
            if (resultTaskPowers != null && resultTaskPowers.Result != null && resultTaskPowers.Result.Count > 0)
            {
                this.IsVisibilityPermission = Visibility.Visible;
            }
        }

        /// <summary>
        /// 页面初始化加载事件
        /// </summary>
        [RelayCommand]
        public async Task ExecuteLoaded()
        {
            if (this.IsLoaded) return;
            //获取编辑权限
            var resultTask = this.InitLoadPermission();
            await resultTask.ConfigureAwait(false);

            //标记初始化加载完成
            this.IsLoaded = true;
            //初始化查询数据
            resultTask = this.QueryData();
            await resultTask.ConfigureAwait(false);
        }

        /// <summary>
        /// 新增命令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteInsert()
        {
            this.IsExecutedIdle = false;
            try
            {
                //编辑弹出层
                SettingSlaveEditorDialog editorDialog = new SettingSlaveEditorDialog("从机设备新增", null);
                bool? bResult = editorDialog.ShowDialog();
                if (!bResult.HasValue || !bResult.Value) return;
                if (editorDialog.DialogResultData == null) return;

                var result = this.SlaveMgr.InsertSlave(editorDialog.DialogResultData);
                await result.ConfigureAwait(false);
                if (result != null && result.Result != null)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        this.SlaveItems.Add(result.Result);
                    }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
                }
            }
            finally
            {
                this.IsExecutedIdle = true;
            }
        }


        /// <summary>
        /// 删除命令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteDelete(MSlave argSlave)
        {
            this.IsExecutedIdle = false;
            try
            {
                var result = this.SlaveMgr.DeleteSlave(argSlave);
                await result.ConfigureAwait(false);
                if (result != null && result.Result)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        this.SlaveItems.Remove(argSlave);
                    }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
                }
                else
                {
                    MessageBox.Show("删除失败！", "警告", MessageBoxButton.OK);
                }
            }
            finally
            {
                this.IsExecutedIdle = true;
            }
        }


        /// <summary>
        /// 编辑命令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteEditor(MSlave argSlave)
        {
            this.IsExecutedIdle = false;
            try
            {
                //编辑弹出层
                SettingSlaveEditorDialog editorDialog = new SettingSlaveEditorDialog("从机设备编辑", argSlave);
                bool? bResult = editorDialog.ShowDialog();
                if (!bResult.HasValue || !bResult.Value) return;
                if (editorDialog.DialogResultData == null) return;

                var result = this.SlaveMgr.UpdateSlave(editorDialog.DialogResultData);
                await result.ConfigureAwait(false);
            }
            finally
            {
                this.IsExecutedIdle = true;
            }
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        public async Task QueryData()
        {
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    this.SlaveItems.Clear();
                    foreach (var item in this.SlaveMgr.Slaves.OrderBy(v => v.ID))
                    {
                        if (item.ID <= 0) continue;
                        this.SlaveItems.Add(item);
                    }
                }
                finally
                {
                    this.IsExecutedIdle = true;
                }
            }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
        }
    }
}
